package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.Room;
import com.zzyl.nursing.mapper.RoomMapper;
import com.zzyl.nursing.service.IRoomService;
import com.zzyl.nursing.vo.BedVo;
import com.zzyl.nursing.vo.DeviceInfo;
import com.zzyl.nursing.vo.RoomVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 房间Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-26
 */
@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements IRoomService {
    @Autowired
    private RoomMapper roomMapper;

    /**
     * 查询房间
     *
     * @param id 房间主键
     * @return 房间
     */
    @Override
    public Room selectRoomById(Long id) {
        return getById(id);
    }

    /**
     * 查询房间列表
     *
     * @param room 房间
     * @return 房间
     */
    @Override
    public List<Room> selectRoomList(Room room) {
        return roomMapper.selectRoomList(room);
    }

    /**
     * 新增房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int insertRoom(Room room) {
        return save(room) ? 1 : 0;
    }

    /**
     * 修改房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int updateRoom(Room room) {
        return updateById(room) ? 1 : 0;
    }

    /**
     * 批量删除房间
     *
     * @param ids 需要删除的房间主键
     * @return 结果
     */
    @Override
    public int deleteRoomByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 根据楼层 id 获取房间视图对象列表
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsByFloorId(Long floorId) {
        return roomMapper.selectByFloorId(floorId);
    }


    /**
     * 获取所有房间（负责老人）
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsWithNurByFloorId(Long floorId) {
        return roomMapper.selectByFloorIdWithNur(floorId);
    }

    /**
     * 根据房间id查询数据
     *
     * @param id
     * @return
     */
    @Override
    public RoomVo getRoomById(Integer id) {
        RoomVo roomVo = roomMapper.getRoomById(id);
        return roomVo;
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 获取房间中的智能设备及数据
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsWithDeviceByFloorId(Long floorId) {
        //1. 查询房间和床位对应的设备信息（基于表查询）
        List<RoomVo> roomVoList = roomMapper.getRoomsWithDeviceByFloorId(floorId);
        if(CollUtil.isEmpty(roomVoList)) {
            return Collections.emptyList();
        }

        //2. 查询设备对应的上报数据信息（基于Redis查询）
        roomVoList.forEach(r->{

            //获取房间下关联的设备列表
            List<DeviceInfo> roomDeviceInfoList = r.getDeviceVos();
            if(CollUtil.isNotEmpty(roomDeviceInfoList)) {
                roomDeviceInfoList.forEach(d->{
                    String iotId = d.getIotId();//获取设备ID（Redis Hash类型的小KEY）

                    //从redis中获取设备对应的最后一次上报的数据（最新数据）
                    String deivceDataListJSON = (String) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_DATA_LATEST,iotId);
                    if(StrUtil.isNotBlank(deivceDataListJSON)) {
                        List<DeviceData> deviceDataList = JSONUtil.toList(deivceDataListJSON, DeviceData.class);
                        d.setDeviceDataVos(deviceDataList);
                    }
                });
            }

            //获取房间下关联的床位列表
            List<BedVo> bedVoList = r.getBedVoList();
            if(CollUtil.isNotEmpty(bedVoList)) {
                bedVoList.forEach(b->{
                    //获取床位下关联的设备列表
                    List<DeviceInfo> bedDeviceInfoList = b.getDeviceVos();
                    if(CollUtil.isNotEmpty(bedDeviceInfoList)) {
                        bedDeviceInfoList.forEach(bd->{
                            String iotId = bd.getIotId();//获取设备ID（Redis Hash类型的小KEY）

                            //从redis中获取设备对应的最后一次上报的数据（最新数据）
                            String deivceDataListJSON = (String) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_DATA_LATEST,iotId);
                            if(StrUtil.isNotBlank(deivceDataListJSON)) {
                                List<DeviceData> deviceDataList = JSONUtil.toList(deivceDataListJSON, DeviceData.class);
                                bd.setDeviceDataVos(deviceDataList);
                            }
                        });
                    }
                });
            }

        });
        return roomVoList;
    }
}
